#include "Object.h"
#include <iostream>
#include "Global.h"
#include "shop.h"
#include "Scene.h"
#include <unistd.h>
#include <limits>
#include <fstream>
#include <sstream>
#include <chrono>
#include <string.h>
extern std::string global_username;
extern std::string global_digit;
extern int pace1,pace2;
Player::Player(int x, int y, const std::string &name, const std::string &Symbol, int HP, int Attack, int defends) : VirtualObject(x, y, name, Symbol, HP, Attack, defends)
{
    money = 50;
    Level = 0;
    b = std::make_unique<Bag>(*this);
    const std::string &c = "宝箱";
    const std::string &d = "📦";
    Box = std::make_shared<TreasureBox>(*this);
}
// Player::~Player()
// {
//     delete b;
// }

void Player::Move()
{   
    pace1 = GetX();
    pace2 = GetY();
    std::cout << "请输入移动方向w上，s下，a左，d右   b背包  u菜单"<<std::endl;
    char c = 0;
    std::cin >> c;
    switch (c)
    {
    case 'w':
        SetY(GetY() - 1);
        break;
    case 's':
        SetY(GetY() + 1);
        break;
    case 'a':
        SetX(GetX() - 1);
        break;
    case 'd':
        SetX(GetX() + 1);
        break;
    case 'b':
        std::cout << "进入背包:" << std::endl;
        GetBag().show();
        break;
    case 'u':
        HandleGameFlow();
        break;
    default:
        break;
    }

    if (GetX() < 0)
        SetX(0);
    if (GetY() < 0)
        SetY(0);
    if (GetX() >= MapSize)
        SetX(MapSize - 1);
    if (GetY() >= MapSize)
        SetY(MapSize - 1);
}

void Player::show()
{
    std::cout << "=========================玩家=============================\n";
    std::cout << "玩家名称:" << GetName() << "|血量:|" << GetHP() << "|" << std::endl;
    std::cout << "攻击力:|" << GetAttack() << "|防御力:|" << Getdefends() << std::endl;
    std::cout << "金钱:|" << Getmoney() << "|" << std::endl;
    std::cout << "等级:|" << GetLevel() << "经验值:|" << GetExp() << std::endl;
}

void Player::HandleGameFlow()
{   
    system("clear");
    while (true) {
        std::cout << "\n";
        std::cout << "███████████████████████████████████████████████████\n";
        std::cout << "█                                                     █\n";
        std::cout << "█   ╔═════════════════════════════════════════════╗   █\n";
        std::cout << "█   ║                Game Menu                    ║   █\n";
        std::cout << "█   ╚═════════════════════════════════════════════╝   █\n";
        std::cout << "█   ╔═════════════════════════════════════════════╗   █\n";
        std::cout << "█   ║  1. 开始游戏                                ║   █\n";
        std::cout << "█   ╠═════════════════════════════════════════════╣   █\n";
        std::cout << "█   ║  2. 继续游戏                                ║   █\n";
        std::cout << "█   ╠═════════════════════════════════════════════╣   █\n";
        std::cout << "█   ║  3. 保存游戏                                ║   █\n";
        std::cout << "█   ╠═════════════════════════════════════════════╣   █\n";
        std::cout << "█   ║  4. 保存且退出                              ║   █\n";
        std::cout << "█   ╚═════════════════════════════════════════════╝   █\n";
        std::cout << "█                                                     █\n";
        std::cout << "███████████████████████████████████████████████████\n";
        std::cout << "请选择一个选项(1-4):  ";

        int choice;
        std::cin >> choice;

        if (std::cin.fail()) {
            std::cin.clear(); // Clear the error flag
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Discard invalid input
            std::cout << "错误的输入，请输入一个1-4之间的选项.\n";
            continue;
        }

        switch (choice) 
        {
            case 1:
                deleteFile();
                SetX(0);
                SetY(0);
                SetName(global_username);
                SetSymbol("👨");
                SetHP(100);
                SetAttack(4);
                Setdefends(1);
                Setmoney(50);
                GetBag().LoadFromFile();
                InitMonsters();
                Box->InitTreasureBoxes();
                return;
            case 2:
                return;
            case 3:
                GetBag().SaveToFile();
                SavePlayerAttributesToFile();
                saveMonsters();
                Box->saveTreasureBoxes();
                return;
            case 4:
                GetBag().SaveToFile();
                SavePlayerAttributesToFile();
                saveMonsters();
                Box->saveTreasureBoxes();
                exit(-1);
            default:
                std::cout << "Invalid choice. Please select an option between 1 and 4.\n";
        }
    }
}

void Monster::show()
{
    std::cout << "=========================怪兽=============================\n";
    std::cout << "怪兽名称:" << GetName() << "|血量:|" << GetHP() << "|" << std::endl;
    std::cout << "攻击力:|" << GetAttack() << "|防御力:|" << Getdefends() << std::endl;
}

Monster::Monster(int x, int y, const std::string &name, const std::string &Symbol, int HP, int Attack, int defends, int Exp, int money)
    : VirtualObject(x, y, name, Symbol, HP, Attack, defends, Exp)
{
    MaxHp = HP;
    Money = money;
}

void Player::LevelUp()
{
    const int baseExp = 100;  // 基础经验值
    const int expIncrement = 50;  // 每级增加的经验值
    const int maxLevel = 10;  // 最大等级
    while (Level < maxLevel)
    {
        int currentLevelExp = baseExp + (Level - 1) * expIncrement;
        
        if (GetExp() < currentLevelExp)
            break;

        Level++;
        SetExp(GetExp() - currentLevelExp);
        printf("恭喜升级到 %d 级!\n", Level);
        
        // 增加生命值
        SetHP(GetHP() + 30);
        
        // 根据当前等级增加攻击力和防御力
        SetAttack(GetAttack() + Level);
        Setdefends(Getdefends() + Level);
        
        if (Level < maxLevel) 
        {
            printf("下一级需要 %d 经验值\n", baseExp + Level * expIncrement);
        } 
        else
        {
            printf("恭喜达到最大等级!\n");
        }
    }

    // 处理超出最大等级的经验值
    if (Level == maxLevel) 
    {
        int maxExp = baseExp + (maxLevel - 1) * expIncrement;
        if (GetExp() > maxExp) 
        {
            SetExp(maxExp);
        }
    }
}

void Player::SavePlayerAttributesToFile()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/玩家坐标.txt";
    std::ofstream file(filename);
    if (file.is_open())
    {
        file << "X:" << GetX() << std::endl;
        file << "Y:" << GetY() << std::endl;
        file << "Name:" << GetName() << std::endl;
        file << "Symbol:" << GetSymbol() << std::endl;
        file << "HP:" << GetHP() << std::endl;
        file << "Attack:" << GetAttack() << std::endl;
        file << "Defends:" << Getdefends() << std::endl;
        file << "Money:" << money << std::endl;
        file << "Level:" << Level << std::endl;
        file << "Exp:" << Exp <<std::endl;
        file.close();
    }
    else
    {
    }
}

void Player::LoadPlayerAttributesFromFile()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/玩家坐标.txt";
    std::ifstream file(filename);
    if (file.is_open())
    {
        std::string line;
        while (std::getline(file, line))
        {
            std::istringstream iss(line);
            std::string key;
            if (std::getline(iss, key, ':'))
            {
                std::string value;
                if (key == "X")
                {
                    int X;
                    iss >> X;
                    SetX(X);
                }
                if (key == "Y")
                {
                    int Y;
                    iss >> Y;
                    SetY(Y);
                }
                if (key == "Name")
                {
                    std::getline(iss, value);
                    SetName(value);
                }
                else if (key == "Symbol")
                {
                    std::getline(iss, value);
                    SetSymbol(value);
                }
                else if (key == "HP")
                {
                    int hp;
                    iss >> hp;
                    SetHP(hp);
                }
                else if (key == "Attack")
                {
                    int attack;
                    iss >> attack;
                    SetAttack(attack);
                }
                else if (key == "Defends")
                {
                    int defends;
                    iss >> defends;
                    Setdefends(defends);
                }
                else if (key == "Money")
                {
                    iss >> money;
                }
                else if (key == "Level")
                {
                    iss >> Level;
                }
                else if (key == "Exp")
                {
                    iss >> Exp;
                }
            }
        }
        file.close();
    }
    else
    {
    }
}

bool Player::exist()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/玩家坐标.txt";
    std::ifstream file(filename);
    bool exists = file.is_open();

    file.close(); // 显式关闭文件流

    return exists;
}

void Player::InitMonsters()
{
    if (!Exits())
    {   
        // 清空当前容器
        monsters.clear();
        for (int i = 0; i < 5; ++i)
        {
            auto [x, y] = generateUniqueCoordinates();
            monsters.push_back(std::make_shared<Monster>(x, y, "哥布林", "🐵", 30, 10, 5, 50, 100));
        }

        for (int i = 0; i < 3; ++i)
        {
            auto [x, y] = generateUniqueCoordinates();

            monsters.push_back(std::make_shared<Monster>(x, y, "骨头骑士", "💀", 100, 20, 10, 100, 200));
        }

        for (int i = 0; i < 2; ++i)
        {
            auto [x, y] = generateUniqueCoordinates();
            monsters.push_back(std::make_shared<Monster>(x, y, "巨龙", "🐲", 200, 30, 20,200, 300));
        }

        auto [x, y] = generateUniqueCoordinates();
        monsters.push_back(std::make_shared<Monster>(x, y, "魔王", "👹", 300, 50, 40, 400, 500));
    }
    else
    {
        loadMonsters();
    }
}

void Player::saveMonsters()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/怪兽属性.txt";
    std::ofstream outFile(filename);
    if (!outFile)
    {
        std::cerr << "无法打开文件进行写入: " << filename << std::endl;
        return;
    }
    // std::cout << "monsters 类型: " << typeid(monsters).name() << ", 大小: " << monsters.size() << std::endl;
    if (!monsters.empty())
    {
        for (const auto &monster : monsters)
        {
            outFile << monster->GetX() << " "
                    << monster->GetY() << " "
                    << monster->GetName() << " "
                    << monster->GetSymbol() << " "
                    << monster->GetHP() << " "
                    << monster->GetAttack() << " "
                    << monster->Getdefends() << " "
                    << monster->GetExp() << " "
                    << monster->GetMoney() << std::endl;
        }
    }
    outFile.close();
}

std::vector<std::shared_ptr<Monster>> Player::loadMonsters()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" +global_digit +"/怪兽属性.txt";
    // std::vector<std::shared_ptr<Monster>> monsters;
    std::ifstream inFile(filename);
    if (!inFile)
    {
        // std::cerr << "无法打开文件进行读取: " << filename << std::endl;
        return monsters;
    }

    while (inFile)
    {
        Monster monster;
        int x, y, hp, attack, defends, exp, money;
        std::string name, symbol;
        inFile >> x >> y >> name >> symbol >> hp >> attack >> defends >> exp >> money;
        // monster.SetX(x);  monster.SetY(y); monster.SetName(name); monster.SetSymbol(symbol); monster.SetHP(hp); monster.SetAttack(attack); monster.Setdefends(defends);
        // monster.SetExp(exp); monster.SetMoney(money);
        if (inFile)
        {
            monsters.push_back(std::make_shared<Monster>(x, y, name, symbol, hp, attack, defends, exp, money));
        }
        // 检查是否成功读取一个怪物的数据
        // if (inFile) {
        //     monsters.push_back(std::make_shared<Monster>(monster));
        // }
    }

    inFile.close();
    return monsters;
}

bool Player::Exits()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/怪兽属性.txt";
    std::ifstream file(filename);
    bool exists = file.good(); // 使用 good() 而不是 is_open()
    
    // if (!exists)
    // {
    //     // std::cerr << "无法打开文件: " << filename << std::endl;
    //     // std::cerr << "错误代码: " << errno << " - " << strerror(errno) << std::endl;
    // }

    file.close();
    return exists;
}

void Player::MonsterShow()
{
    for (auto &ite : monsters)
    {
        if (ite->GetHP() > 0)
            Map[ite->GetY()][ite->GetX()] = ite->GetSymbol();
    }
}

void Player::RefreshMonster(Monster *m)
{
    // 将所有怪物的当前坐标添加到usedCoordinates集合中
    usedCoordinates.clear();
    for (const auto &monster : monsters)
    {
        usedCoordinates.insert({monster->GetX(), monster->GetY()});
    }

    // 生成新的唯一坐标
    auto [x, y] = generateUniqueCoordinates();
    m->SetHP(m->GetMaxHp()); // 重置怪物的生命值
    m->SetX(x);              // 设置怪物的新X坐标
    m->SetY(y);              //
}

void Player::deleteFile()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filePath1 = archiveDir + "/" + username + "/" + global_digit + "/宝箱属性.txt";
    std::string filePath2 = archiveDir + "/" + username + "/" + global_digit + "/怪兽属性.txt";  
    std::string filePath3 = archiveDir + "/" + username + "/" + global_digit + "/玩家数据.txt"; 
    std::string filePath4 = archiveDir + "/" + username + "/" + global_digit + "/玩家坐标.txt";

    std::remove(filePath1.c_str());
    std::remove(filePath2.c_str());
    std::remove(filePath3.c_str());
    std::remove(filePath4.c_str());
}

std::pair<int, int> Player::generateUniqueCoordinates()
{
    int x, y;
    int attempts = 0;
    unsigned long long int seed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    srand(seed); // 使用时间作为种子
    do
    {
        x = rand() % MapSize;
        y = rand() % MapSize;
        if (attempts > MapSize * MapSize)
        {
            std::cerr << "Error: Unable to find unique coordinates after many attempts." << std::endl;
            exit(1); // 防止无限循环，退出程序
        }
    } while (usedCoordinates.count({x, y}) > 0|| (x == 0 && (y == 0 || y == 2))); // 重复时重新生成
    usedCoordinates.insert({x, y});
    return {x, y};
}

void Bag::Remove(size_t index)
{
    if (index < 1 || index > props.size())
    {
        std::cout << "无效的索引\n";
        return;
    }

    props.erase(props.begin() + index - 1);

    // Adjust numbers after removal
    for (size_t i = index - 1; i < props.size(); ++i)
    {
        props[i]->Setnumber_(i + 1);
    }

    // Reset nextNumber to the last index + 1
    nextNumber_ = props.size() + 1;
}
void Bag::RemoveL()
{
    Remove(props.size());
}
void Bag::show()
{

    while (1)
    {
        system("clear");
        if (props.empty())
        {
            std::cout << "空空如也" << std::endl;
        }
        else
        {
            for (const auto &prop : props)
            {
                prop->show();
            }
        }
        std::cout << "====================背包=======================\n";
        std::cout << "1、装备\n";
        std::cout << "2、卸下\n";
        std::cout << "3、丢弃\n";
        std::cout << "4、退出\n";
        std::cout << "请选择您要进行的操作（输入对应数字）：\n";
        int c = 0;
        std::cin >> c;
        if (std::cin.fail())
        {
            std::cin.clear();                                                   // 清除错误状态
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 丢弃错误输入
            std::cout << "无效的选择，请重新输入。\n";
            sleep(1);
            continue; // 继续循环
        }
        switch (c)
        {
        case 1:
        {
            std::cout << "请选择你要装备的商品序列号\n";
            int index = 0;
            std::cin >> index;
            Equip(index);
        }
        break;
        case 2:
        {
            ShowEquippedItems();
            std::cout << "请选择你要卸下的商品序列号\n";
            int index = 0;
            std::cin >> index;
            Unequip(index);
        }
        break;
        case 3:
        {
            std::cout << "请选择你要丢弃的商品序列号\n";
            int index = 0;
            std::cin >> index;
            Remove(index);
        }
        break;
        case 4:
            return;
        default:
            std::cout << "无效的选择，请重新输入。\n";
            break;
        }
        sleep(1);
    }
}

void Bag::SaveToFile()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/玩家数据.txt";
    std::ofstream file(filename);

    if (!file)
    {
        std::cerr << "无法打开文件 " << filename << " 进行写入\n";
        return;
    }

    // 写入 props
    file << "Props:\n";
    for (const auto &prop : props)
    {
        if (prop->GetAttack())
        {
            file << "A" << " " << prop->Getnumber_() << " " << prop->Getname_() << " " << prop->Getmoney_() << " " << prop->GetAttack() << "\n";
        }

        if (prop->GetDefends())
        {
            file << "B" << " " << prop->Getnumber_() << " " << prop->Getname_() << " " << prop->Getmoney_() << " " << prop->GetDefends() << "\n";
        }

        if (prop->GetHP())
        {
            file << "C" << " " << prop->Getnumber_() << " " << prop->Getname_() << " " << prop->Getmoney_() << " " << prop->GetHP() << "\n";
        }
    }

    // 写入 equippedItems
    file << "EquippedItems:\n";
    for (const auto &equipped : equippedItems)
    {
        if (equipped->GetAttack())
        {
            file << "A" << " " << equipped->Getnumber_() << " " << equipped->Getname_() << " " << equipped->Getmoney_() << " " << equipped->GetAttack() << "\n";
        }

        if (equipped->GetDefends())
        {
            file << "B" << " " << equipped->Getnumber_() << " " << equipped->Getname_() << " " << equipped->Getmoney_() << " " << equipped->GetDefends() << "\n";
        }

        if (equipped->GetHP())
        {
            file << "C" << " " << equipped->Getnumber_() << " " << equipped->Getname_() << " " << equipped->Getmoney_() << " " << equipped->GetHP() << "\n";
        }
    }

    file.close();
}

void Bag::LoadFromFile()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/玩家数据.txt";
    std::ifstream file(filename);

    if (!file)
    {   
        // 清空当前容器
        props.clear();
        equippedItems.clear();
        return;
    }

    // 清空当前容器
    props.clear();
    equippedItems.clear();

    std::string line;
    while (std::getline(file, line))
    {
        if (line == "Props:")
        {
            while (std::getline(file, line) && line != "EquippedItems:")
            {
                std::istringstream iss(line);
                char itemType;
                iss >> itemType;
                int number;
                std::string name;
                int money;
                if (itemType == 'A')
                {
                    int attrack;
                    iss >> number >> name >> money >> attrack;
                    props.push_back(std::make_shared<Weapon>(money, name, number, attrack));
                }
                if (itemType == 'B')
                {
                    int defends;
                    iss >> number >> name >> money >> defends;
                    props.push_back(std::make_shared<Defencer>(money, name, number, defends));
                }
                if (itemType == 'C')
                {
                    int HP;
                    iss >> number >> name >> money >> HP;
                    props.push_back(std::make_shared<Medicine>(money, name, number, HP));
                }
            }
        }
        if (line == "EquippedItems:")
        {
            while (std::getline(file, line))
            {
                std::istringstream iss(line);
                char itemType;
                iss >> itemType;
                int number;
                std::string name;
                int money;
                if (itemType == 'A')
                {
                    int attrack;
                    iss >> number >> name >> money >> attrack;
                    equippedItems.push_back(std::make_shared<Weapon>(money, name, number, attrack));
                }
                if (itemType == 'B')
                {
                    int defends;
                    iss >> number >> name >> money >> defends;
                    equippedItems.push_back(std::make_shared<Defencer>(money, name, number, defends));
                }
                if (itemType == 'C')
                {
                    int HP;
                    iss >> number >> name >> money >> HP;
                    equippedItems.push_back(std::make_shared<Medicine>(money, name, number, HP));
                }
            }
        }
    }

    file.close();
}

void Bag::Insert(const PropPtr &p)
{
    // 检查props是否为空
    if (!props.empty())
    {
        // 获取最后一个元素的number
        auto ite = props.back();
        if (ite->Getnumber_() > 0)
        {
            // 增加当前道具的number
            int a = ite->Getnumber_();
            p->Setnumber_(a + 1);
        }
        else
        {
            // 如果最后一个元素的number不大于0，设置为下一个number
            p->Setnumber_(nextNumber_++);
        }
    }
    else
    {
        // 如果props为空，设置当前道具的number为下一个number
        p->Setnumber_(nextNumber_++);
    }
    // 将道具添加到vector中
    props.push_back(p);
}

void Bag::Equip(size_t index)
{
    if (index < 1 || index > props.size())
    {
        std::cout << "无效的索引\n";
        return;
    }
    auto item = props[index - 1];
    equippedItems.push_back(item); // 将装备放入已装备的容器中
    if (item->GetAttack())
    {
        p.SetAttack(p.GetAttack() + item->GetAttack());
    }
    if (item->GetDefends())
    {
        p.Setdefends(p.Getdefends() + item->GetDefends());
    }
    if (item->GetHP())
    {
        p.SetHP(p.GetHP() + item->GetHP());
        equippedItems.pop_back();
    }
    props.erase(props.begin() + index - 1);
    // 调整序号
    if (index <= props.size())
    {
        for (size_t i = index - 1; i < props.size(); ++i)
        {
            props[i]->Setnumber_(i + 1);
        }
    }
    if (props.size() == 0)
    {
        nextNumber_ = 1;
    }
    // 确保 equippedItems 的序号连续
    for (size_t i = 0; i < equippedItems.size(); ++i)
    {
        equippedItems[i]->Setnumber_(i + 1);
    }
}

void Bag::Unequip(size_t index)
{
    if (index < 1 || index > equippedItems.size())
    {
        std::cout << "无效的装备索引\n";
        return;
    }
    auto item = equippedItems[index - 1];
    props.push_back(item); // 将装备放回背包中
    if (item->GetAttack())
    {
        p.SetAttack(p.GetAttack() - item->GetAttack());
    }
    if (item->GetDefends())
    {
        p.Setdefends(p.Getdefends() - item->GetDefends());
    }
    equippedItems.erase(equippedItems.begin() + index - 1);
    // 调整序号
    for (size_t i = index - 1; i < equippedItems.size(); ++i)
    {
        equippedItems[i]->Setnumber_(i + 1);
    }
    // 确保 props 的序号连续
    for (size_t i = 0; i < props.size(); ++i)
    {
        props[i]->Setnumber_(i + 1);
    }
}

void Bag::ShowEquippedItems()
{
    std::cout << "已装备的装备:\n";
    for (const auto &item : equippedItems)
    {
        std::cout << "序号 " << item->Getnumber_() << " 名称 " << item->Getname_() << " 金钱 " << item->Getmoney_() << std::endl; // 展示每个装备的信息
    }
}

void TreasureBox::RemoveFromScene()
{
    int index = GetTreasureBoxIndex(this);
    if (index != -1)
    {
        p.Box->RemoveTreasureBox(index);
    }
}

void TreasureBox::InitTreasureBoxes()
{
    if (!ExistTreasureBoxes())
    {   
        treasureBoxes.clear();
        // 使用当前时间初始化随机数生成器
        std::srand(static_cast<unsigned int>(std::time(nullptr)));
        for (int i = 0; i < 5; ++i)
        {
            int x = std::rand() % MapSize;
            int y = std::rand() % MapSize;
            do
            {
                x = std::rand() % MapSize;
                y = std::rand() % MapSize;
            } while (isOverlap(treasureBoxes, x, y)|| (x == 0 && (y == 0 || y == 2)));
            const std::string c = "宝箱";
            const std::string d = "📦";
            // 创建并添加宝箱
            auto treasureBox = std::make_shared<TreasureBox>(x, y, c, d, p);
            treasureBoxes.push_back(treasureBox);
        }
    }
    else
    {
        p.Box->loadTreasureBoxes(treasureBoxes);
    }
}

bool TreasureBox::isOverlap(std::vector<std::shared_ptr<TreasureBox>> &treasureBoxes, int x, int y)
{
    for (const auto &box : treasureBoxes)
    {
        if (box->GetX() == x && box->GetY() == y)
        {
            return true; // 发现重叠
        }
    }
    return false;
}

void TreasureBox::RemoveTreasureBox(int index)
{   
    if (index >= 0 && index < treasureBoxes.size())
    {
        treasureBoxes.erase(treasureBoxes.begin() + index);
    }
}

int TreasureBox::GetTreasureBoxIndex(TreasureBox *t)
{
    auto &treasureBoxes = p.Box->GetTrea();
    for (int i = 0; i < treasureBoxes.size(); ++i)
    {
        if (treasureBoxes[i].get() == t)
        {
            return i;
        }
    }
    return -1;
}

void TreasureBox::saveTreasureBoxes()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/宝箱属性.txt";
    std::ofstream outFile(filename);
    if (!outFile)
    {
        throw std::runtime_error("无法打开文件进行写入");
    }

    for (const auto &box : treasureBoxes)
    {
        // 假设 TreasureBox 类有 getX(), getY(), getName(), 和 getSymbol() 方法
        outFile << box->GetX() << ' '
                << box->GetY() << ' '
                << box->GetName() << ' '
                << box->GetSymbol() << '\n';
    }

    outFile.close();
}

void TreasureBox::loadTreasureBoxes(std::vector<std::shared_ptr<TreasureBox>> &treasureBoxes)
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit +"/宝箱属性.txt";
    std::ifstream inFile(filename);
    if (!inFile)
    {
        throw std::runtime_error("无法打开文件进行读取");
    }

    int x, y;
    std::string name, symbol;
    std::string line;

    while (std::getline(inFile, line))
    {
        std::istringstream iss(line);
        if (!(iss >> x >> y >> name >> symbol))
        {
            throw std::runtime_error("文件格式错误");
        }

        // 创建并添加宝箱
        auto treasureBox = std::make_shared<TreasureBox>(x, y, name, symbol, p);
        treasureBoxes.push_back(treasureBox);
    }
    const std::string c = "宝箱";
    const std::string d = "📦";
    // 创建并添加宝箱
    auto treasureBox = std::make_shared<TreasureBox>(2, 6, c, d, p);
    treasureBoxes.push_back(treasureBox);

    inFile.close();
}

bool TreasureBox::ExistTreasureBoxes()
{
    std::string archiveDir = "存档"; // 使用 std::string 来表示存档目录

    std::string username = global_username;
    // 构建文件名，假设存档目录为 "Username/"，文件名为 "玩家数据.txt"
    std::string filename = archiveDir + "/" + username + "/" + global_digit + "/宝箱属性.txt";
    std::ifstream file(filename);
    bool exists = file.is_open();

    file.close(); // 显式关闭文件流

    return exists;
}
